/**
 * @file resize.cpp
 * @brief 图像缩放模块实现
 * 
 * 实现最近邻插值的图像降采样。
 * 将图像面积缩小至 1/4（长宽各缩至 1/SCALE_FACTOR）。
 */
#include "resize.h"
#include <platform.h>


void downscaleImage(
    const unsigned char fullImage[IMAGE_HEIGHT][IMAGE_WIDTH],
    int top, int bottom,
    unsigned char scaledImage[][SCALED_WIDTH],
    int& newHeight
)
{

    
    int cropHeight = bottom - top;
    newHeight = cropHeight / SCALE_FACTOR;  // 向下取整
    const int newWidth = SCALED_WIDTH;
    
    // ===== 简化版：2×2中值滤波 =====
 
    
    for (int outRow = 0; outRow < newHeight; ++outRow) {
        // 对应原图顶行
        int srcRow0 = top + outRow * SCALE_FACTOR;
        
        for (int outCol = 0; outCol < newWidth; ++outCol) {
            int srcCol0 = outCol * SCALE_FACTOR;
            
            // 获取2×2区域的4个像素（带边界保护）
            int r0 = srcRow0;
            int r1 = srcRow0 + 1;
            if (r0 < top) r0 = top;
            if (r1 >= bottom) r1 = bottom - 1;
            
            int c0 = srcCol0;
            int c1 = srcCol0 + 1;
            if (c0 < 0) c0 = 0;
            if (c1 >= IMAGE_WIDTH) c1 = IMAGE_WIDTH - 1;
            
            // 提取2×2像素值
            unsigned char p1 = fullImage[r0][c0];
            unsigned char p2 = fullImage[r0][c1];
            unsigned char p3 = fullImage[r1][c0];
            unsigned char p4 = fullImage[r1][c1];
            
            // 2×2中值滤波：6次比较排序
            // 排序网络：确保最少比较次数
            if (p1 > p2) { unsigned char tmp = p1; p1 = p2; p2 = tmp; }
            if (p3 > p4) { unsigned char tmp = p3; p3 = p4; p4 = tmp; }
            if (p1 > p3) { unsigned char tmp = p1; p1 = p3; p3 = tmp; }
            if (p2 > p4) { unsigned char tmp = p2; p2 = p4; p4 = tmp; }
            if (p2 > p3) { unsigned char tmp = p2; p2 = p3; p3 = tmp; }
            
            // p2就是中值（排序后：p1 ≤ p2 ≤ p3 ≤ p4）
            scaledImage[outRow][outCol] = p2;
        }
    }
    
}